package com.youi.webbg;

import com.alibaba.fastjson.JSONObject;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.entity.Goods;
import com.youi.entity.Goodssize;
import com.youi.entity.Groupleader;
import com.youi.entity.Leaderfan;
import com.youi.entity.Leaderprofit;
import com.youi.entity.Leaderprofitdetail;
import com.youi.entity.Leaderstore;
import com.youi.entity.Merchant;
import com.youi.entity.Ordergoods;
import com.youi.entity.Orderprofitdetail;
import com.youi.entity.Purchasehistory;
import com.youi.entity.Refundorder;
import com.youi.entity.User;
import com.youi.entity.Userorder;
import com.youi.entity.Userorderexcel;
import com.youi.entity.Userwechat;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.exception.BusinessException;
import com.youi.service.GoodsService;
import com.youi.service.GoodssizeService;
import com.youi.service.GroupleaderService;
import com.youi.service.LeaderfanService;
import com.youi.service.LeaderprofitService;
import com.youi.service.LeaderprofitdetailService;
import com.youi.service.LeaderstoreService;
import com.youi.service.MerchantService;
import com.youi.service.OrdergoodsService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.PurchasehistoryService;
import com.youi.service.RefundorderService;
import com.youi.service.SetleaderlevelService;
import com.youi.service.UserService;
import com.youi.service.UserorderService;
import com.youi.service.UserorderexcelService;
import com.youi.service.UserwechatService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.service.impl.TransactionalUserorderService;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.util.DateUtil;
import com.youi.util.LogUtil;
import com.youi.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时器
 *
 * @author XJY
 */
@Controller
public class TimeController {


    @Autowired
    private OrdergoodsService ordergoodsService;
    @Autowired
    private UserorderService userorderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodssizeService goodssizeService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private LeaderprofitService leaderprofitService;
    @Autowired
    private LeaderprofitdetailService leaderprofitdetailService;
    @Autowired
    private OrderprofitdetailService orderprofitdetailService;
    @Autowired
    private LeaderstoreService leaderstoreService;
    @Autowired
    private YibaorefundService yibaorefundService;
    @Autowired
    private RefundorderService refundorderService;
    @Autowired
    private GroupleaderService groupleaderService;
    @Autowired
    private LeaderfanService leaderfanService;
    @Autowired
    private UserwechatService userwechatService;
    @Autowired
    private UserService userService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private PurchasehistoryService purchasehistoryService;
    @Autowired
    private SetleaderlevelService setleaderlevelService;
    @Autowired
    private UserorderexcelService userorderexcelService;

    @Autowired
    private TransactionalUserorderService transactionalUserorderService;


    private static Integer CANCEL = -1;//已关闭
    private static Integer NOPAY = 0;//待付款
    private static Integer PAID = 1; //待发货


    /**
     * 超过15分钟未支付的订单自动取消关闭
     *
     * @throws IOException
     */

    @Scheduled(cron = "0 */1 * * * ?")
    public void timeMethod() throws IOException {
        cancelautoUserorder();
        setOrderToSaleAfter();
        setUserorderToReceiving();
        //startBuyGoods();
        //endBuyGoods();
        //setSellOutGoods();
    }


    /**
     * 5分钟执行一次的任务
     *
     * @throws IOException
     * @throws BusinessException
     */

    @Scheduled(cron = "0 */5 * * * ?")
    public void fiveMinute() throws IOException, BusinessException {
        getPaidOrder();
        getRefundOrder();
        deleteUserorderexcel();
    }

    /**
     * 每天凌晨1点05分执行的任务
     *
     * @throws IOException
     */
    @Scheduled(cron = "0 5 1 * * ?")
    public void daytimeMethod() throws IOException {
        setUserorderToWithdraw();
    }

    /**
     * 取消订单
     *
     * @throws IOException
     */
    public void cancelautoUserorder() throws IOException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, NOPAY);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtOrder", DateUtil.getCalendarByAdd(new Date(), Calendar.MINUTE, -16));
        List<Userorder> userorderList = userorderService.getByParamsAll(params, null, null, null, endTime);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                params = new HashMap<String, Object>();
                params.put(Common.DELSTATUS, DelStatus.NODEL);
                Map<String, Object> searchParams = new HashMap<String, Object>();
                searchParams.put("orderNos", userorder.getOrderNo());
                Yibaopayment yibaopayment = yibaopaymentService.getByParam(params, searchParams, null);
                if (yibaopayment != null) {
                    JSONObject jsonObject = YibaopayUtil.getYibaoorder(yibaopayment.getSerialNumber(), yibaopayment.getPaymentNo());
                    if (jsonObject != null && jsonObject.getString("code").equals("OPR00000")) {
                        if (jsonObject.getString("status").equals("SUCCESS")) {
                            userorder.setStatus(PAID);
                            userorderService.saveOrUpdate(userorder);
                            continue;
                        }
                    }
                }

                transactionalUserorderService.cancelUserOrder(userorder, false);
//				userorderService.getUserorderMsg(userorder);
//				userorder.setStatus(CANCEL);
//				for (Ordergoods ordergoods : userorder.getOrdergoodsList()) {
//					Goods goods=goodsService.get(ordergoods.getGoodsId());
//					if (goods!=null) {
//						Map<String, Object> prams=new HashMap<String, Object>();
//						prams.put(Common.DELSTATUS, DelStatus.NODEL);
//						prams.put("goodsId", goods.getId());
//						prams.put("specification", ordergoods.getSpecification());
//						prams.put("price", ordergoods.getSlaePrice());
//						Goodssize goodssize=goodssizeService.getByParam(prams);
//						if (goodssize!=null) {
//							if (goodssize.getRealStockNum()!=null) {
//								goodssize.setRealStockNum(goodssize.getRealStockNum()+ordergoods.getCount());
//							}
//							if (goodssize.getSaleNum()!=null) {
//								goodssize.setSaleNum(goodssize.getSaleNum()-ordergoods.getCount());
//							}
//							goods.setRealSaleCnt(goods.getRealSaleCnt()-ordergoods.getCount());
//							goodssizeService.saveOrUpdate(goodssize);
//							goodsService.saveOrUpdate(goods);
//						}
//					}
//				}
            }
//			userorderService.saveOrUpdateAll(userorderList); 因为之前transactionalUserorderService已经保存了每一个userorder
        }
    }

    /**
     * 收货7天后把订单变为可提现订单
     */
    public void setUserorderToWithdraw() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, Arrays.asList(3, 4, 5));
        params.put("merchantStatus", 0);
        params.put("platformStatus", 0);
        params.put("refund", -1);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtComplete", DateUtil.getCalendarByAdd(new Date(), Calendar.DATE, -7));
        List<Userorder> userorderList = userorderService.getByParamsAll(params, null, null, null, endTime);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                userorder.setMerchantStatus(Common.TRUE);
                userorder.setPlatformStatus(Common.TRUE);
                userorder.setGmtUnfreeze(new Date());
                params = new HashMap<String, Object>();
                params.put(Common.DELSTATUS, DelStatus.NODEL);
                params.put("orderNo", userorder.getOrderNo());
                Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(params);
                if (orderprofitdetail != null) {
                    //判断是否有一级佳选官的id
                    if (orderprofitdetail.getLeaderId1() != null) {
                        params = new HashMap<String, Object>();
                        params.put(Common.DELSTATUS, DelStatus.NODEL);
                        params.put("leaderId", orderprofitdetail.getLeaderId1());
                        Leaderprofit firstLeaderprofit = leaderprofitService.getByParam(params);
                        if (firstLeaderprofit != null) {
                            if (firstLeaderprofit.getFrozen() - orderprofitdetail.getFirstAmount() > 0) {
                                firstLeaderprofit.setFrozen(firstLeaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                                firstLeaderprofit.setBalance(firstLeaderprofit.getBalance() + orderprofitdetail.getFirstAmount());
                                firstLeaderprofit.setGmtModify(new Date());
                                leaderprofitService.saveOrUpdate(firstLeaderprofit);
                            }
                        }
                    }
                    //判断是否有二级佳选官的id
                    if (orderprofitdetail.getLeaderId2() != null) {
                        params = new HashMap<String, Object>();
                        params.put(Common.DELSTATUS, DelStatus.NODEL);
                        params.put("leaderId", orderprofitdetail.getLeaderId2());
                        Leaderprofit secondLeaderprofit = leaderprofitService.getByParam(params);
                        if (secondLeaderprofit != null) {
                            if (secondLeaderprofit.getFrozen() - orderprofitdetail.getSecondAmount() > 0) {
                                secondLeaderprofit.setFrozen(secondLeaderprofit.getFrozen() - orderprofitdetail.getSecondAmount());
                                secondLeaderprofit.setBalance(secondLeaderprofit.getBalance() + orderprofitdetail.getSecondAmount());
                                secondLeaderprofit.setGmtModify(new Date());
                                leaderprofitService.saveOrUpdate(secondLeaderprofit);
                            }
                        }
                    }
                }

            }
            userorderService.saveOrUpdateAll(userorderList);
        }
    }

    /**
     * 发货7天后未确认收货的订单转为确认收货
     */
    public void setUserorderToReceiving() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, 2);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtShipment", DateUtil.getCalendarByAdd(new Date(), Calendar.DATE, -7));
        List<Userorder> userorderList = userorderService.getByParamsAll(params, null, null, null, endTime);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                userorder.setGmtReceiving(new Date());
                userorder.setGmtComplete(new Date());
                userorder.setStatus(3);
            }
            userorderService.saveOrUpdateAll(userorderList);
        }
    }

    /**
     * 把开售的商品转为出售中
     */
    @Deprecated
    public void startBuyGoods() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, 4);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtStart", DateUtil.simpdfyMdHms.format(new Date()));
        List<Goods> goodsList = goodsService.getByParamsAll(params, null, null, null, endTime);
        if (goodsList != null && goodsList.size() > 0) {
            for (Goods goods : goodsList) {
                goods.setStatus(1);
                goodsService.saveOrUpdate(goods);
            }
        }
    }

    /**
     * 把时间到了的商品转为已结束
     */
    @Deprecated
    public void endBuyGoods() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, 1);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtEnd", DateUtil.simpdfyMdHms.format(new Date()));
        List<Goods> goodsList = goodsService.getByParamsAll(params, null, null, null, endTime);
        if (goodsList != null && goodsList.size() > 0) {
            for (Goods goods : goodsList) {
                goods.setStatus(5);
                goodsService.saveOrUpdate(goods);
            }
        }
    }

    /**
     * 把库存为0的商品变为已售罄
     */
    @Deprecated
    public void setSellOutGoods() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, 1);
        List<Goods> goodsList = goodsService.getByParams(params);
        if (goodsList == null || goodsList.size() == 0) {
            return;
        }
        for (Goods goods : goodsList) {
            params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put("goodsId", goods.getId());
            List<Goodssize> goodssizeList = goodssizeService.getByParams(params);
            if (goodssizeList == null || goodssizeList.size() == 0) {
                return;
            }
            Integer allStockNum = 0;
            for (Goodssize goodssize : goodssizeList) {
                if (goodssize.getRealStockNum() != null) {
                    allStockNum += goodssize.getRealStockNum();
                }
            }
            goods.setAllStockNum(allStockNum);
            if (goods.getAllStockNum() <= 0) {
                goods.setStatus(2);
                goodsService.saveOrUpdate(goods);
            }
        }
    }

    /**
     * 检测是否支付后未更新状态的订单
     *
     * @throws IOException
     * @throws BusinessException
     */
    public void getPaidOrder() throws IOException, BusinessException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, NOPAY);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                params = new HashMap<String, Object>();
                params.put(Common.DELSTATUS, DelStatus.NODEL);
                Map<String, Object> searchParams = new HashMap<String, Object>();
                searchParams.put("orderNos", userorder.getOrderNo());
                Yibaopayment yibaopayment = yibaopaymentService.getByParam(params, searchParams, null);
                if (yibaopayment != null) {
                    JSONObject jsonObject = YibaopayUtil.getYibaoorder(yibaopayment.getSerialNumber(), yibaopayment.getPaymentNo());
                    if (jsonObject != null && jsonObject.getString("code").equals("OPR00000")) {
                        if (jsonObject.getString("status").equals("SUCCESS")) {
                            userorder.setStatus(PAID);
                            userorderService.saveOrUpdate(userorder);
                            params = new HashMap<String, Object>();
                            params.put(Common.DELSTATUS, DelStatus.NODEL);
                            params.put("orderNo", userorder.getOrderNo());
                            Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(params);
                            if (orderprofitdetail == null) {
                                params = new HashMap<String, Object>();
                                params.put(Common.DELSTATUS, DelStatus.NODEL);
                                params.put(Common.USERID, userorder.getUserId());
                                Userwechat userwechat = userwechatService.getByParam(params);
                                Merchant merchant = merchantService.get(userorder.getMerchantId());
                                User user = userService.get(userorder.getUserId());
                                getLoginMsg(user);
                                checkFans(userorder.getUnioid(), userorder, user);
                                getLeaderprofit(userorder, userorder.getPayableAmount(), user, merchant, userwechat);
                                addBuyHistory(user, userorder);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 将团长冻结的佣金转入可提现佣金
     */
    public void setFreezeToUnfreeze() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.TYPE, 0);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put(Common.GMTCREATED, DateUtil.getCalendarByAdd(new Date(), Calendar.DATE, -7));
        List<Leaderprofitdetail> leaderprofitdetailList = leaderprofitdetailService.getByParamsAll(params, null, null, null, endTime);
        if (leaderprofitdetailList != null && leaderprofitdetailList.size() > 0) {
            for (Leaderprofitdetail leaderprofitdetail : leaderprofitdetailList) {
                params = new HashMap<String, Object>();
                params.put(Common.DELSTATUS, DelStatus.NODEL);
                params.put("leaderId", leaderprofitdetail.getLeaderId());
                Leaderprofit leaderprofit = leaderprofitService.getByParam(params);
                if (leaderprofit != null) {
                    leaderprofit.setFrozen(leaderprofit.getFrozen() - leaderprofitdetail.getAmount());
                    leaderprofit.setBalance(leaderprofit.getBalance() + leaderprofitdetail.getAmount());
                }
                leaderprofitService.saveOrUpdate(leaderprofit);
            }
        }
    }


    /**
     * 检测是否退款后未更新状态的订单
     *
     * @throws IOException
     */
    public void getRefundOrder() throws IOException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put("refund", 1);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                Map<String, Object> prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                Map<String, Object> searchParams = new HashMap<String, Object>();
                searchParams.put("orderNos", userorder.getOrderNo());
                Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
                if (yibaopayment != null) {
                    Map<String, Object> otherparams = new HashMap<String, Object>();
                    otherparams.put(Common.DELSTATUS, DelStatus.NODEL);
                    otherparams.put("orderNo", userorder.getOrderNo());
                    Yibaorefund yibaorefund = yibaorefundService.getByParam(otherparams);
                    if (yibaorefund != null) {
                        JSONObject data = YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
                        if (data != null && data.getString("code").equals("OPR00000")) {
                            if (data.getString("status").equals("SUCCESS")) {
                                if (userorder.getRefund() == 1) {
                                    userorder.setRefund(2);
                                    userorderService.saveOrUpdate(userorder);
                                    yibaorefund.setStatus(data.getString("status"));
                                    yibaorefundService.saveOrUpdate(yibaorefund);
                                    userorder.setRefund(2);
                                    userorderService.saveOrUpdate(userorder);
                                    yibaorefund.setStatus(data.getString("status"));
                                    yibaorefund.setRefundAmount(data.getString("realRefundAmount"));
                                    yibaorefundService.saveOrUpdate(yibaorefund);
                                    prams = new HashMap<String, Object>();
                                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                                    prams.put("orderNo", userorder.getOrderNo());
                                    Refundorder refundorder = refundorderService.getByParam(prams);
                                    if (refundorder != null) {
                                        refundorder.setStatus(1);
                                        refundorder.setRefundAmount(Double.valueOf(yibaorefund.getRefundAmount()));
                                        refundorderService.saveOrUpdate(refundorder);
                                        LogUtil.Info("=========退款执行成功===========");
                                    }
                                }
                            } else if (data.getString("status").equals("REJECT")) {
                                userorder.setRefund(-2);
                                userorderService.saveOrUpdate(userorder);
                                yibaorefund.setStatus(data.getString("status"));
                                yibaorefundService.saveOrUpdate(yibaorefund);
                                prams = new HashMap<String, Object>();
                                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                                prams.put("orderNo", userorder.getOrderNo());
                                Refundorder refundorder = refundorderService.getByParam(prams);
                                if (refundorder != null) {
                                    refundorder.setStatus(-2);
                                    refundorderService.saveOrUpdate(refundorder);
                                    LogUtil.Info("=========退款执行成功===========");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 把过了售后期的订单设置为售后期过期
     */
    public void setOrderToSaleAfter() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, Arrays.asList(3, 4));
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put("gmtOrder", DateUtil.getCalendarByAdd(new Date(), Calendar.DATE, -15));
        List<Userorder> userorderList = userorderService.getByParamsAll(params, null, null, null, endTime);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                userorder.setIsAfterSale(Common.TRUE);
            }
            userorderService.saveOrUpdateAll(userorderList);
        }
    }


    public void setRefundOrder() throws IOException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put("refund", 1);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList != null && userorderList.size() > 0) {
            for (Userorder userorder : userorderList) {
                Map<String, Object> prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("orderNo", userorder.getOrderNo());
                prams.put(Common.STATUS, 0);
                Refundorder refundorder = refundorderService.getByParam(prams);
                if (refundorder != null) {
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    Map<String, Object> searchParams = new HashMap<String, Object>();
                    searchParams.put("orderNos", refundorder.getOrderNo());
                    Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
                    if (yibaopayment != null) {
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("uniqueOrderNo", yibaopayment.getPaymentNo());
                        Yibaorefund yibaorefund = yibaorefundService.getByParam(prams);
                        if (yibaorefund != null) {
                            JSONObject data = YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
                            if (data != null && data.getString("code").equals("OPR00000")) {
                                if (data.getString("status").equals("SUCCESS")) {
                                    if (userorder.getRefund() == 1) {
                                        Integer check = getLeaderprofitBack(userorder);
                                        if (check == 1) {
                                            userorder.setRefund(2);
                                            userorderService.saveOrUpdate(userorder);
                                            yibaorefund.setStatus(data.getString("status"));
                                            yibaorefundService.saveOrUpdate(yibaorefund);
                                            userorder.setRefund(2);
                                            userorder.setGmtRefund(new Date());
                                            userorderService.saveOrUpdate(userorder);
                                            refundorder.setStatus(1);
                                            refundorderService.saveOrUpdate(refundorder);
                                            yibaorefund.setStatus(data.getString("status"));
                                            yibaorefundService.saveOrUpdate(yibaorefund);
                                            System.out.println("=========退款执行成功===========");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除过期的导出记录
     */
    public void deleteUserorderexcel() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        Map<String, Object> endTime = new HashMap<String, Object>();
        endTime.put(Common.GMTCREATED, DateUtil.getCalendarByAdd(new Date(), Calendar.DATE, -1));
        List<Userorderexcel> userorderexcelList = userorderexcelService.getByParamsAll(params, null, null, null, endTime);
        if (userorderexcelList != null && userorderexcelList.size() > 0) {
            for (Userorderexcel userorderexcel : userorderexcelList) {
                String objectName = userorderexcel.getPathUrl().substring(27, userorderexcel.getPathUrl().length());
                OSSUtil.deleteUpload(objectName);
                if (!OSSUtil.existObject(objectName)) {
                    userorderexcel.setDelStatus(DelStatus.DEL);
                    userorderexcelService.saveOrUpdate(userorderexcel);
                }
            }
        }
    }

    /**
     * 判断佣金退回执行是否成功
     *
     * @param userorder
     * @return
     */
    private Integer getLeaderprofitBack(Userorder userorder) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", userorder.getOrderNo());
        Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(prams);
        if (orderprofitdetail != null) {
            User user = userService.get(userorder.getUserId());
            if (user != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put(Common.USERID, user.getId());
                Userwechat userwechat = userwechatService.getByParam(prams);
                if (userwechat != null) {
                    Integer identity = checkUserIidentity(userorder.getUserId());
                    if (identity == 1) {
                        getLeaderprofitBackToUser(userwechat, userorder, orderprofitdetail);
                        return 1;
                    } else if (identity == 2) {
                        getBackLeaderprofitToUser(userorder, orderprofitdetail);
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 当用户为粉丝时退回佣金信息
     *
     * @param userwechat
     * @param userorder
     * @param orderprofitdetail
     */
    private void getLeaderprofitBackToUser(Userwechat userwechat, Userorder userorder, Orderprofitdetail orderprofitdetail) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("unionid", userwechat.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        if (leaderfan != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.ID, leaderfan.getLeaderId());
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", groupleader.getId());
                Map<String, Object> sortParams = new HashMap<String, Object>();
                sortParams.put(Common.ID, Common.DESC);
                Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
                if (leaderstore != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //查询团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit != null) {
                            //添加团长佣金信息
                            leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                            leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                            //添加团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(groupleader.getId(), 2, -orderprofitdetail.getFirstAmount(), "退款支出", userorder.getOrderNo()));
                        }
                    } else if (leaderstore.getLevel() == 2) {
                        //当团长为二级团长时
                        //5.退回二级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit != null) {
                            leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getSecondAmount());
                            leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getSecondAmount());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                            //添加二级团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2,
                                    -orderprofitdetail.getSecondAmount(), "退款支出", userorder.getOrderNo()));
                        }
                        //6.退回一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, topLeaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        if (firstGroupleader != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit != null) {
                                topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setFrozen(topleaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                                //添加顶级团长佣金流水
                                leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "退款支出", userorder.getOrderNo()));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 当订单用户身份是团长的时候
     *
     * @param userorder
     * @param orderprofitdetail
     */
    private void getBackLeaderprofitToUser(Userorder userorder, Orderprofitdetail orderprofitdetail) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userorder.getUserId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        //查询下单人团长信息
        if (groupleader != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            Map<String, Object> sortParams = new HashMap<String, Object>();
            sortParams.put(Common.ID, Common.DESC);
            Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
            if (leaderstore != null) {
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", leaderstore.getLeaderId());
                Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                if (leaderprofit != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //添加团长佣金信息
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                        leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "佣金退回", userorder.getOrderNo()));
                    } else if (leaderstore.getLevel() == 2) {
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() - orderprofitdetail.getSecondAmount());
                        leaderprofit.setFrozen(leaderprofit.getFrozen() - orderprofitdetail.getSecondAmount());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加二级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 2, -orderprofitdetail.getSecondAmount(), "佣金退回", userorder.getOrderNo()));
                        //6.添加一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        if (topLeaderstore != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit != null) {
                                //添加顶级团长佣金信息
                                topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() - orderprofitdetail.getFirstAmount());
                                topleaderprofit.setFrozen(topleaderprofit.getFrozen() - orderprofitdetail.getFirstAmount());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                                //添加顶级团长佣金流水
                                leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 2, -orderprofitdetail.getFirstAmount(), "佣金退款", userorder.getOrderNo()));
                            }
                        }
                    }
                }
            }
        }
    }

    private void getLoginMsg(User user) throws BusinessException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        Userwechat userother = userwechatService.getByParam(prams);
        user.setUnionId(userother.getUnionid());
        if (groupleader != null) {
            user.setLeaderId(groupleader.getId());
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            List<Leaderstore> leaderstoreList = leaderstoreService.getByParams(prams);
            for (Leaderstore leaderstore : leaderstoreList) {
                if (leaderstore.getLevel() == 1) {
                    user.setLeaderLevel(1);
                } else if (leaderstore.getLevel() == 2) {
                    user.setLeaderLevel(2);
                }
                break;
            }
        } else {
            user.setLeaderLevel(0);
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        LogUtil.Info("unionid=" + userother.getUnionid());
        prams.put("unionid", userother.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        LogUtil.Info("leaderfan=" + leaderfan);
        if (leaderfan == null) {
            LogUtil.Info("验证是否粉丝");
            user.setIsFans(0);
        } else {
            user.setIsFans(1);
        }

    }

    /**
     * 检测订单用户身份
     *
     * @param userId
     * @return 0非粉丝 1粉丝 2团长
     */
    private Integer checkUserIidentity(Long userId) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userId);
        Userwechat userother = userwechatService.getByParam(prams);
        if (userother != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("unionid", userother.getUnionid());
            Leaderfan leaderfan = leaderfanService.getByParam(prams);
            if (leaderfan != null) {
                return 1;
            }
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.USERID, userId);
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                return 2;
            }
        }
        return 0;
    }

    /**
     * 团长佣金计算方法
     *
     * @param amount
     * @param userwechat
     * @param orderprofitdetail
     * @param userorder
     * @param payAmount
     * @param merchantComms
     * @param serviceCharge
     * @param platComms
     */
    private void getleaderComms(Userwechat userwechat, Orderprofitdetail orderprofitdetail, Userorder userorder, Double payAmount, Double merchantComms, Double serviceCharge, Double platComms) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("unionid", userwechat.getUnionid());
        Leaderfan leaderfan = leaderfanService.getByParam(prams);
        if (leaderfan != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.ID, leaderfan.getLeaderId());
            Groupleader groupleader = groupleaderService.getByParam(prams);
            if (groupleader != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", groupleader.getId());
                Map<String, Object> sortParams = new HashMap<String, Object>();
                sortParams.put(Common.ID, Common.DESC);
                Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
                if (leaderfan != null) {
                    if (leaderstore.getLevel() == 1) {
                        //订单为一级团长订单时
                        //查询团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit == null) {
                            leaderprofit = new Leaderprofit(userorder.getLeaderId());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                        }
                        //计算团长佣金
                        //1.确定团长佣金比例
                        Double topLeaderRate = ObjectUtil.sciCal(setleaderlevelService.getLeaderRate(1) + setleaderlevelService.getLeaderRate(2), 2);
                        //2.计算团长佣金
                        Double leaderComms = ObjectUtil.sciCal(payAmount * (topLeaderRate * 0.01), 2);
                        //3.计算平台佣金
                        platComms = ObjectUtil.sciCal(payAmount - merchantComms - leaderComms - serviceCharge, 2);
                        //添加团长佣金信息
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + leaderComms);
                        leaderprofit.setFrozen(leaderprofit.getFrozen() + leaderComms);
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0, leaderComms, "佣金收入", userorder.getOrderNo()));
                        //添加分佣记录
                        orderprofitdetail = new Orderprofitdetail(0, userorder.getOrderNo(), userorder.getPayableAmount());
                        orderprofitdetail.setLeaderId1(leaderstore.getLeaderId());
                        if (groupleader != null) {
                            orderprofitdetail.setFirstUser(groupleader.getName());
                        }
                        orderprofitdetail.setFirstAmount(Double.valueOf(leaderComms));
                        orderprofitdetail.setPlatAmount(platComms);
                        orderprofitdetail.setMerchantId(userorder.getMerchantId());
                        orderprofitdetail.setMerAmount(merchantComms);
                        orderprofitdetail.setServiceCharge(serviceCharge);
                        orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                    } else if (leaderstore.getLevel() == 2) {
                        //当团长为二级团长时
                        //1.确定二级团长的佣金
                        Double secondLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(2) * 0.01), 2);
                        //2.确定一级团长佣金
                        Double firstLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(1) * 0.01), 2);
                        //3.计算一二级团长佣金的总和
                        Double allLeaderComms = ObjectUtil.sciCal(secondLeaderComms + firstLeaderComms, 2);
                        //4.计算平台佣金
                        platComms = ObjectUtil.sciCal(payAmount - merchantComms - allLeaderComms - serviceCharge, 2);
                        //5.添加二级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", leaderstore.getLeaderId());
                        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                        if (leaderprofit == null) {
                            leaderprofit = new Leaderprofit(userorder.getLeaderId());
                            leaderprofitService.saveOrUpdate(leaderprofit);
                        }
                        leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + secondLeaderComms);
                        leaderprofit.setFrozen(leaderprofit.getFrozen() + secondLeaderComms);
                        leaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(leaderprofit);
                        //添加二级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0,
                                secondLeaderComms, "佣金收入", userorder.getOrderNo()));
                        //6.添加一级团长佣金信息
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("storeId", leaderstore.getStoreId());
                        prams.put("level", 1);
                        Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, leaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        if (firstGroupleader != null) {
                            prams = new HashMap<String, Object>();
                            prams.put(Common.DELSTATUS, DelStatus.NODEL);
                            prams.put("leaderId", topLeaderstore.getLeaderId());
                            Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                            if (topleaderprofit == null) {
                                topleaderprofit = new Leaderprofit(topLeaderstore.getLeaderId());
                                leaderprofitService.saveOrUpdate(topleaderprofit);
                            }
                            //添加顶级团长佣金信息
                            topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() + firstLeaderComms);
                            topleaderprofit.setFrozen(topleaderprofit.getFrozen() + firstLeaderComms);
                            topleaderprofit.setGmtModify(new Date());
                            leaderprofitService.saveOrUpdate(topleaderprofit);
                            //添加顶级团长佣金流水
                            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 0, firstLeaderComms, "佣金收入", userorder.getOrderNo()));
                            //添加分佣记录
                            orderprofitdetail = new Orderprofitdetail(1, userorder.getOrderNo(), userorder.getPayableAmount());
                            orderprofitdetail.setLeaderId1(topLeaderstore.getLeaderId());
                            if (groupleader != null) {
                                orderprofitdetail.setFirstUser(firstGroupleader.getName());
                            }
                            orderprofitdetail.setFirstAmount(firstLeaderComms);
                            orderprofitdetail.setLeaderId2(leaderstore.getLeaderId());
                            orderprofitdetail.setSecondUser(groupleader.getName());
                            orderprofitdetail.setSecondAmount(secondLeaderComms);
                            orderprofitdetail.setPlatAmount(platComms);
                            orderprofitdetail.setMerchantId(userorder.getMerchantId());
                            orderprofitdetail.setMerAmount(merchantComms);
                            orderprofitdetail.setServiceCharge(serviceCharge);
                            orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取自己是团长的佣金
     *
     * @param amount
     * @param userwechat
     * @param orderprofitdetail
     * @param userorder
     * @param payAmount
     * @param merchantComms
     * @param serviceCharge
     * @param platComms
     */
    private void getLeaderOneselfComms(Userwechat userwechat, Orderprofitdetail orderprofitdetail, Userorder userorder, Double payAmount, Double merchantComms, Double serviceCharge, Double platComms) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, userorder.getUserId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        //查询下单人团长信息
        if (groupleader != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            Map<String, Object> sortParams = new HashMap<String, Object>();
            sortParams.put(Common.ID, Common.DESC);
            Leaderstore leaderstore = leaderstoreService.getByParam(prams, null, sortParams);
            if (leaderstore != null) {
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("leaderId", leaderstore.getLeaderId());
                Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
                if (leaderprofit == null) {
                    leaderprofit = new Leaderprofit(leaderstore.getLeaderId());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                }
                if (leaderstore.getLevel() == 1) {
                    //订单为一级团长订单时
                    //计算团长佣金
                    //1.确定团长佣金比例
                    Double topLeaderRate = ObjectUtil.sciCal(setleaderlevelService.getLeaderRate(1) + setleaderlevelService.getLeaderRate(2), 2);
                    //2.计算团长佣金
                    Double leaderComms = ObjectUtil.sciCal(payAmount * (topLeaderRate * 0.01), 2);
                    //3.计算平台佣金
                    platComms = ObjectUtil.sciCal(payAmount - merchantComms - leaderComms - serviceCharge, 2);
                    //添加团长佣金信息
                    leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + leaderComms);
                    leaderprofit.setFrozen(leaderprofit.getFrozen() + leaderComms);
                    leaderprofit.setGmtModify(new Date());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                    //添加团长佣金流水
                    leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0, leaderComms, "佣金收入", userorder.getOrderNo()));
                    //添加分佣记录
                    orderprofitdetail = new Orderprofitdetail(0, userorder.getOrderNo(), userorder.getPayableAmount());
                    orderprofitdetail.setLeaderId1(leaderstore.getLeaderId());
                    if (groupleader != null) {
                        orderprofitdetail.setFirstUser(groupleader.getName());
                    }
                    orderprofitdetail.setFirstAmount(leaderComms);
                    orderprofitdetail.setPlatAmount(platComms);
                    orderprofitdetail.setMerchantId(userorder.getMerchantId());
                    orderprofitdetail.setMerAmount(merchantComms);
                    orderprofitdetail.setServiceCharge(serviceCharge);
                    orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                } else if (leaderstore.getLevel() == 2) {
                    //二级团长分佣流程
                    //1.确定二级团长的佣金
                    Double secondLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(2) * 0.01), 2);
                    //2.确定一级团长佣金
                    Double firstLeaderComms = ObjectUtil.sciCal(payAmount * (setleaderlevelService.getLeaderRate(1) * 0.01), 2);
                    //3.计算一二级团长佣金的总和
                    Double allLeaderComms = ObjectUtil.sciCal(secondLeaderComms + firstLeaderComms, 2);
                    //4.计算平台佣金
                    platComms = ObjectUtil.sciCal(payAmount - merchantComms - allLeaderComms - serviceCharge, 2);
                    //5.添加二级团长佣金信息
                    leaderprofit.setTotalAmount(leaderprofit.getTotalAmount() + secondLeaderComms);
                    leaderprofit.setFrozen(leaderprofit.getFrozen() + secondLeaderComms);
                    leaderprofit.setGmtModify(new Date());
                    leaderprofitService.saveOrUpdate(leaderprofit);
                    //添加二级团长佣金流水
                    leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderstore.getLeaderId(), 0,
                            secondLeaderComms, "佣金收入", userorder.getOrderNo()));
                    //6.添加一级团长佣金信息
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    prams.put("storeId", leaderstore.getStoreId());
                    prams.put("level", 1);
                    Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
                    if (topLeaderstore != null) {
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put(Common.ID, topLeaderstore.getLeaderId());
                        Groupleader firstGroupleader = groupleaderService.getByParam(prams);
                        prams = new HashMap<String, Object>();
                        prams.put(Common.DELSTATUS, DelStatus.NODEL);
                        prams.put("leaderId", topLeaderstore.getLeaderId());
                        Leaderprofit topleaderprofit = leaderprofitService.getByParam(prams);
                        if (topleaderprofit == null) {
                            topleaderprofit = new Leaderprofit(topLeaderstore.getLeaderId());
                            leaderprofitService.saveOrUpdate(topleaderprofit);
                        }
                        //添加顶级团长佣金信息
                        topleaderprofit.setTotalAmount(topleaderprofit.getTotalAmount() + firstLeaderComms);
                        topleaderprofit.setFrozen(topleaderprofit.getFrozen() + firstLeaderComms);
                        topleaderprofit.setGmtModify(new Date());
                        leaderprofitService.saveOrUpdate(topleaderprofit);
                        //添加顶级团长佣金流水
                        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(topLeaderstore.getLeaderId(), 0, firstLeaderComms, "佣金收入", userorder.getOrderNo()));
                        //添加分佣记录
                        orderprofitdetail = new Orderprofitdetail(1, userorder.getOrderNo(), userorder.getPayableAmount());
                        orderprofitdetail.setLeaderId1(topLeaderstore.getLeaderId());
                        if (groupleader != null) {
                            orderprofitdetail.setFirstUser(firstGroupleader.getName());
                        }
                        orderprofitdetail.setFirstAmount(firstLeaderComms);
                        orderprofitdetail.setLeaderId2(leaderstore.getLeaderId());
                        orderprofitdetail.setSecondUser(groupleader.getName());
                        orderprofitdetail.setSecondAmount(secondLeaderComms);
                        orderprofitdetail.setPlatAmount(platComms);
                        orderprofitdetail.setMerchantId(userorder.getMerchantId());
                        orderprofitdetail.setMerAmount(merchantComms);
                        orderprofitdetail.setServiceCharge(serviceCharge);
                        orderprofitdetailService.saveOrUpdate(orderprofitdetail);
                    }
                }
            }
        }
    }

    /**
     * 验证是否粉丝
     *
     * @param unionid 用户unionid
     * @param orderNo 订单号
     */
    public void checkFans(String unionid, Userorder userorder, User user) {
        if (userorder.getLeaderId() != null && user.getLeaderLevel() == 0) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.UNIONID, unionid);
            Leaderfan leaderfan = leaderfanService.getByParam(prams);
            if (leaderfan == null) {
                leaderfan = new Leaderfan(userorder.getLeaderId(), unionid);
            } else {
                leaderfan.setOrderCount(leaderfan.getOrderCount() + 1);
                leaderfan.setGmtLatsBuy(new Date());
            }
            leaderfanService.saveOrUpdate(leaderfan);
        }
    }


    /**
     * 团长佣金信息分账
     */
    public void getLeaderprofit(Userorder userorder, Double payAmount, User user, Merchant merchant, Userwechat userwechat) {
        Orderprofitdetail orderprofitdetail = null;
        //商家佣金
        Double merchantComms = ObjectUtil.sciCal(payAmount * (1 - (merchant.getCommissionRatio() * 0.01)), 2);
        //手续费
        Double serviceCharge = ObjectUtil.sciCal(payAmount * 0.003, 2);
        Double platComms = null;
        //判断用户身份
        Integer identity = checkUserIidentity(userorder.getUserId());
        if (identity == 0) {
            //当用户为非粉丝和非团长时
            platComms = ObjectUtil.sciCal(payAmount - merchantComms - serviceCharge, 2);//平台佣金
            orderprofitdetail = new Orderprofitdetail(2, userorder.getOrderNo(), userorder.getPayableAmount());
            orderprofitdetail.setPlatAmount(platComms);
            orderprofitdetail.setMerchantId(userorder.getMerchantId());
            orderprofitdetail.setMerAmount(merchantComms);
            orderprofitdetail.setServiceCharge(serviceCharge);
            orderprofitdetailService.saveOrUpdate(orderprofitdetail);
        } else if (identity == 1) {
            //当用户为粉丝的时候
            getleaderComms(userwechat, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge, platComms);
        } else if (identity == 2) {
            //当用户为团长的时候
            getLeaderOneselfComms(userwechat, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge, platComms);
        }
    }

    /**
     * 添加购买记录
     *
     * @param user
     * @param userorder
     */
    public void addBuyHistory(User user, Userorder userorder) {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderId", userorder.getId());
        List<Ordergoods> ordergoodsList = ordergoodsService.getByParams(prams);
        if (ordergoodsList != null && ordergoodsList.size() > 0) {
            for (Ordergoods ordergoods : ordergoodsList) {
                purchasehistoryService.saveOrUpdate(new Purchasehistory(user.getId(), ordergoods.getGoodsId(), ordergoods.getCount()));
            }
        }
    }
}
